import os
import json
from datetime import datetime


class DataComparator:
    @staticmethod
    def get_latest_file(path, folder_name):
        folder_path = os.path.join(path, folder_name)
        files = os.listdir(folder_path)
        if not files:
            return None
        
        files_with_dates = []
        for file in files:
            date_string = file.split('_')[0]
            try:
                date = datetime.strptime(date_string, "%Y%m%d")
                files_with_dates.append((file, date))
            except ValueError:
                pass

        if not files_with_dates:
            return None
        
        latest_file = max(files_with_dates, key=lambda x: x[1])[0]
        return latest_file

    @staticmethod
    def load_data(file_path):
        with open(file_path, "r", encoding="utf-8") as file:
            data = json.load(file)
        return data

    @staticmethod
    def compare_data(new_data, old_data):
        return new_data == old_data

    @staticmethod
    def get_data_diff(old_data, new_data):
        differences = []

        old_data_dict = {item["BH"]: item for item in old_data}
        new_data_dict = {item["BH"]: item for item in new_data}

        for bh, new_item in new_data_dict.items():
            if bh in old_data_dict:
                old_item = old_data_dict[bh]

                for key, value in new_item.items():
                    if key not in old_item or old_item[key] != value:
                        differences.append((bh, key, old_item.get(key), value))
            else:
                differences.append((bh, "新条目", None, new_item))

        for bh, old_item in old_data_dict.items():
            if bh not in new_data_dict:
                differences.append((bh, "删除条目", old_item, None))

        return differences
